package com.qf.config;

/**
 * @author lyx
 * @date 2022/7/11 16:50
 */

import com.qf.job.MyJob;
import org.apache.shardingsphere.elasticjob.api.JobConfiguration;
import org.apache.shardingsphere.elasticjob.lite.api.bootstrap.impl.ScheduleJobBootstrap;
import org.apache.shardingsphere.elasticjob.reg.base.CoordinatorRegistryCenter;
import org.apache.shardingsphere.elasticjob.reg.zookeeper.ZookeeperConfiguration;
import org.apache.shardingsphere.elasticjob.reg.zookeeper.ZookeeperRegistryCenter;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * ElasticJob分布式任务调度初始化配置
 * @author zhaojian
 */
@Component
public class ElasticJobConfig {

    /**
     * 配置Zookeeper注册协调中心
     * @return
     */
    @Bean(initMethod = "init")
    public CoordinatorRegistryCenter createRegistryCenter() {

        ZookeeperConfiguration zkconfig = new ZookeeperConfiguration("192.168.200.129:2181", "my-job");
        //最大重试次数
        zkconfig.setMaxRetries(3);
        //连接超时时间
        zkconfig.setConnectionTimeoutMilliseconds(600000);
        //会话超时时间
        zkconfig.setSessionTimeoutMilliseconds(600000);
        //最大超时时间
        zkconfig.setMaxSleepTimeMilliseconds(60000);

        CoordinatorRegistryCenter regCenter = new ZookeeperRegistryCenter(zkconfig);
        regCenter.init();
        return regCenter;
    }

    /**
     * 创建ElasticJob初始化对象
     * 指定任务的分片信息以及执行的周期
     */
    @Bean
    public JobConfiguration createJobConfiguration() {
        JobConfiguration jobConfiguration = JobConfiguration
                .newBuilder("MyJob", 3)
                .cron("0/3 * * * * ?").build();
        return jobConfiguration;
    }

    /**
     * 将Zookeeper，执行的任务，JobConfiguration配置到ScheduleJobBootstrap中：
     * @param registryCenter 注册调度中心对象
     * @param myJob 自定义业务任务对象
     * @param config 初始化对象
     * @return
     */
    @Bean(initMethod = "schedule")
    public ScheduleJobBootstrap scheduleJobBootstrap(CoordinatorRegistryCenter registryCenter,
                                                     MyJob myJob,
                                                     JobConfiguration config) {
        ScheduleJobBootstrap scheduleJobBootstrap = new ScheduleJobBootstrap(registryCenter, myJob, config);
        return scheduleJobBootstrap;
    }
}